import fs from 'fs'
import * as cheerio from 'cheerio'
import { Analyzer } from './crowller'

interface CourseData {
  title: string
  count: number
}

interface CourseInfo {
  time: number
  data: CourseData[]
}

interface Content {
  [propsName: number]: CourseData[]
}

export default class AAnalyzer implements Analyzer {
  private getCourseData(html: string) {
    const $ = cheerio.load(html)
    const courseItems = $('.course-item')
    const courseData: CourseData[] = []
    courseItems.map((index, el) => {
      const desc = $(el).find('.course-desc')
      const title = desc.eq(0).text()
      const count = parseInt(desc.eq(1).text().split('：')[1], 10)
      courseData.push({
        title,
        count
      })
    })

    return {
      time: new Date().getTime(),
      data: courseData
    }
  }

  generateJsonContent(courseInfo: CourseInfo, filePath: string) {
    let fileContent: Content = {}
    if (fs.existsSync(filePath)) {
      fileContent = JSON.parse(fs.readFileSync(filePath, 'utf-8'))
    }
    fileContent[courseInfo.time] = courseInfo.data
    return fileContent
  }

  public anylyze(html: string, filePath: string) {
    const courseInfo = this.getCourseData(html)
    const fileContent = this.generateJsonContent(courseInfo, filePath)
    return JSON.stringify(fileContent)
  }
}
